package com.wurd.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.wurd.test.exception.WxException;
import com.wurd.test.wx.token.TokenBuilder;
import com.wurd.test.wx.utils.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/wxcallback")
@Slf4j
public class WxCallBackController {

    @Autowired
    private TokenBuilder tokenBuilder;

    /**
     * 路径不可变，wx固定
     * 授权事件接收配置
     * 接收ComponentVerifyTicket
     * 有效期12小时
     *
     * @param obj
     * @return
     */
    @PostMapping(value = "/component", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public String wxVerifyTicketJson(@RequestBody JSONObject obj) {
        log.debug("component：{}", obj.toString());
        String ticket = obj.getString("ComponentVerifyTicket");
        long createTs = obj.getLongValue("CreateTime");
        if (ticket == null) {
            System.out.println("ComponentVerifyTicket error");
            return "success";
        }
        tokenBuilder.buildVerifyTicket(ticket, createTs, 12L * 60 * 60);
        return "success";
    }

    @PostMapping(value = "/component", consumes = {MediaType.TEXT_XML_VALUE})
    public String wxVerifyTicketXml(HttpServletRequest request, @RequestBody String xml) {
        log.debug("component", xml);
        try {
            String msg_signature = request.getParameter("msg_signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String decMsg = EncryptUtils.decrypt(xml, msg_signature, timestamp, nonce);
            log.debug("component：{}", decMsg);
            org.json.JSONObject obj = XML.toJSONObject(decMsg).getJSONObject("xml");
            String ticket = obj.getString("ComponentVerifyTicket");
            long createTs = obj.getLong("CreateTime");
            if (ticket == null) {
                System.out.println("ComponentVerifyTicket error");
                return "success";
            }
            tokenBuilder.buildVerifyTicket(ticket, createTs, 12L * 60 * 60);
        } catch (WxException e) {
            log.error("ComponentVerifyTicket error", e);
            return "success";
        }
        return "success";
    }

    /**
     * 路径不可变，wx固定
     * 消息与事件接收配置
     * 消息事件推送
     *
     * @param obj
     * @return
     */
    @PostMapping(value = "/biz/{appId}", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public String messageEvent(HttpServletRequest request,
                               @PathVariable("appId") String appId,
                               @RequestBody JSONObject obj
    ) {
        log.debug("wxcallback/biz/{appId}：{}", appId);
        log.debug("wxcallback/biz/{appId}：{}", obj.toString());
        if ("text".equals(obj.getString("MsgType"))) {
            if ("ureq0783rjoirenkjfdnvdsaf".equals(obj.getString("Content"))) {
                return "<xml>" +
                        "<ToUserName><![CDATA[" + obj.getString("FromUserName") + "]]></ToUserName>" +
                        "<FromUserName><![CDATA[" + obj.getString("ToUserName") + "]]></FromUserName>" +
                        "<CreateTime>" + obj.getLongValue("CreateTime") + "</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[11111]]></Content>" +
                        "</xml>";
            }
            return "<xml>" +
                    "<ToUserName><![CDATA[" + obj.getString("FromUserName") + "]]></ToUserName>" +
                    "<FromUserName><![CDATA[" + obj.getString("ToUserName") + "]]></FromUserName>" +
                    "<CreateTime>" + obj.getLongValue("CreateTime") + "</CreateTime>" +
                    "<MsgType><![CDATA[text]]></MsgType>" +
                    "<Content><![CDATA[" +
                    "              *          \n" +
                    "           *     *       \n" +
                    "       *             *   \n" +
                    " *  时间不多了   *         \n" +
                    " *  " + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + " * \n" +
                    "       *             *   \n" +
                    "           *     *       \n" +
                    "              *          " +
                    "]]></Content>" +
                    "</xml>";
        }
        return "success";
    }

    @PostMapping(value = "/biz/{appId}", consumes = {MediaType.TEXT_XML_VALUE})
    public String messageEventXml(HttpServletRequest request,
                                  @PathVariable("appId") String appId,
                                  @RequestBody String xml
    ) {
        log.debug("wxcallback/biz/{appId}", appId);
        log.debug("wxcallback/biz/{appId}", xml);
        try {
            String msg_signature = request.getParameter("msg_signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String decMsg = EncryptUtils.decrypt(xml, msg_signature, timestamp, nonce);
            log.debug("wxcallback/biz/{appId}", decMsg);
            org.json.JSONObject obj = XML.toJSONObject(decMsg).getJSONObject("xml");
            if ("text".equals(obj.getString("MsgType"))) {
                String resMsg = "<xml>" +
                        "<ToUserName><![CDATA[" + obj.getString("FromUserName") + "]]></ToUserName>" +
                        "<FromUserName><![CDATA[" + obj.getString("ToUserName") + "]]></FromUserName>" +
                        "<CreateTime>" + obj.getLong("CreateTime") + "</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[" +
                        "              *          \n" +
                        "           *     *       \n" +
                        "       *             *   \n" +
                        " *  时间不多了   *         \n" +
                        " *  " + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + " * \n" +
                        "       *             *   \n" +
                        "           *     *       \n" +
                        "              *          " +
                        "]]></Content>" +
                        "</xml>";
                return EncryptUtils.encrypt(resMsg, obj.getLong("CreateTime") + "", "");
            }
        } catch (WxException e) {
            log.error("消息处理异常", e);
            return "success";
        }
        return "success";
    }

}
